from django.shortcuts import render
import datetime, time, json, urllib.parse
from django.db.models import Q
from tools.methods import create_md5, RuleProcessor, vail_rule
from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from collect.website.models import WebsiteList, RuleList
from tools.callback import api_callback, page_callback
from tools.result import HttpResponseCMD, Code, Message
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.http import require_GET, require_POST
from tools.parameter import parse_parameter, check_parameter, match_parameter


@require_GET
@parse_parameter
@check_parameter({
    'website_id': 'length[0-9999999]'
}, page_callback)
def node_list(request, parameter):
    """网站节点列表"""
    query = RuleList.objects.filter(**parameter).order_by('-create_time').values()
    website_data = WebsiteList.objects.get(website_id=parameter['website_id'])
    return render(request, 'node_list.html', {'node_list': query, 'website_id': parameter['website_id'], 'website_data': model_to_dict(website_data)})


@require_POST
@parse_parameter
@match_parameter({
    'website_id': 'length[0-9999999]',
    'column_name': 'length[0-9999999]',
    'column_url': 'length[0-9999999]',
    'node_type': 'range[0-9999999]',
    'column_rule_type': 'range[0-9999999]',
    'column_rule': 'length[0-9999999]',
    'column_prefix': 'length[0-9999999]',
    'page_rule': 'length[0-9999999]',
    'list_rule_type': 'range[0-9999999]',
    'list_rule': 'length[0-9999999]',
    'list_prefix': 'length[0-9999999]',
    'city': 'length[0-9999999]',
    'gender': 'length[0-9999999]',
    'season': 'length[0-9999999]',
}, api_callback)
def create_node(request, parameter):
    if parameter['node_type'] != 2:
        parameter['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        parameter['collect_status'] = 1
        RuleList.objects.create(**parameter)
        return redirect('/website/node_list?website_id={}'.format(parameter['website_id']))
    else:
        parameter = json.loads(RuleProcessor(parameter).to_json())
        parameter['column_url'] = parameter['detail_url']
        del parameter['detail_url']
        parameter['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        parameter['collect_status'] = 1
        parameter['column_name'] = '详情规则'
        RuleList.objects.create(**parameter)
        return HttpResponseCMD(Code.success, Message.success, parameter).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'id': 'length[0-999999]'
}, api_callback)
def open_edit_node(request, parameter):
    query = RuleList.objects.get(id=parameter['id'])
    result = model_to_dict(query)
    if result['node_type'] == 2:
        name_dict = {'brand': '品牌', 'name': '商品名称', 'pubdate': '发布时间', 'title': '标题', 'desc': '内容', 'images': '图片', 'source_url': '详情原链接'}
        config_lis = []
        for config in eval(result['column_rule']):
            config['name'] = name_dict[config['field']]
            config_lis.append(config)
        result['column_rule'] = config_lis
        return render(request, 'edit_node.html', result)
    return render(request, 'edit_node.html', model_to_dict(query))


@require_POST
@parse_parameter
@match_parameter({
    'id': 'range[0-9999999]',
    'website_id': 'length[0-9999999]',
    'column_name': 'length[0-9999999]',
    'column_url': 'length[0-9999999]',
    'node_type': 'range[0-9999999]',
    'column_rule_type': 'range[0-9999999]',
    'column_rule': 'length[0-9999999]',
    'column_prefix': 'length[0-9999999]',
    'page_rule': 'length[0-9999999]',
    'list_rule_type': 'range[0-9999999]',
    'list_rule': 'length[0-9999999]',
    'list_prefix': 'length[0-9999999]',
    'city': 'length[0-9999999]',
    'gender': 'length[0-9999999]',
    'season': 'length[0-9999999]',
}, api_callback)
def edit_node_api(request, parameter):
    try:
        parameter['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        RuleList.objects.filter(id=parameter['id']).update(**parameter)
        return redirect('/website/node_list?website_id={}'.format(parameter['website_id']))
    except Exception as e:
        print(e)
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'id': 'length[0-999999]'
}, api_callback)
def delete_node(request, parameter):
    try:
        RuleList.objects.filter(id=parameter['id']).delete()
        return HttpResponseCMD(Code.success, Message.success, '删除成功').to_response()
    except Exception as e:
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@check_parameter({
    'id': 'length[0-999999]',
    'collect_status': 'range[0-999999]'
}, api_callback)
def update_node_status(request, parameter):
    try:
        query = RuleList.objects.get(id=parameter['id'])
        query.collect_status = parameter['collect_status']
        query.save()
        return HttpResponseCMD(Code.success, Message.success, model_to_dict(query)).to_response()
    except Exception as e:
        print(e)
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()


@require_GET
@parse_parameter
@match_parameter({
    'website_id': 'length[0-9999999]',
    'column_name': 'length[0-9999999]',
    'column_url': 'length[0-9999999]',
    'node_type': 'range[0-9999999]',
    'column_rule_type': 'range[0-9999999]',
    'column_rule': 'length[0-9999999]',
    'column_prefix': 'length[0-9999999]',
    'page_rule': 'length[0-9999999]',
    'list_rule_type': 'range[0-9999999]',
    'list_rule': 'length[0-9999999]',
    'list_prefix': 'length[0-9999999]',
    'detail_url': 'length[0-9999999]',
}, api_callback)
def check_rule(request, parameter):
    try:
        result = vail_rule(parameter)
        return HttpResponseCMD(Code.success, Message.success, result).to_response()
    except Exception as e:
        print(e)
        return HttpResponseCMD(Code.system_error, Message.system_error, e).to_response()
